﻿/*----------------------------------------------------------------
//  <copyright file="RoleAuthorizationFilter.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2024-03-04 14:51</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud.Hangfire.Dashboard.Authorization
{
    #region "Dashboard角色权限过滤器"
    /// <summary>
    /// Dashboard角色权限过滤器
    /// </summary>
    public class RoleAuthorizationFilter : IDashboardAuthorizationFilter
    {
        /// <summary>
        /// 角色信息
        /// </summary>
        private readonly string[] _roles = Array.Empty<string>();

        #region "构造函数"
        #region "初始化一个Dashboard角色权限过滤器的新实例"
        /// <summary>
        /// 初始化一个Dashboard角色权限过滤器 <see cref="RoleAuthorizationFilter"/> 的新实例
        /// </summary>
        /// <param name="roles">角色信息</param>
        public RoleAuthorizationFilter(string[] roles)
        {
            _roles = roles;
        }
        #endregion

        #endregion

        #region "方法"
        #region "授权"
        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool Authorize(DashboardContext context)
        {
            HttpContext httpContext = context.GetHttpContext();
            ClaimsPrincipal principal = httpContext.User;
            if (principal.Identity is not ClaimsIdentity identity)
            {
                return false;
            }

            OnlineRole[] roles = identity.GetRoles();
            //return _roles.Intersect(roles).Any();
            return roles.Any(o => _roles.Contains(o.Name));
        }
        #endregion

        #endregion

    }
    #endregion

}
